// shopPages/payCode/payCode.js
import {
  baseUrl,
  get_open_id,
  user_login,
  unified_order,
  unified_order_v4

} from "../../utils/api.js";
import {
  MD5
} from '../../utils/MD5.js'
const app = getApp()
var mg_uid = 0;
var btn_status = 1;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    mg_uid: 0,
    authSettingUser: 1,
    mg_info: [],
    integral: '',
    money: '',
    moneys: '0.00', //合计
    desc: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    mg_uid = 0;
    btn_status = 1;
    var scene = decodeURIComponent(options.scene);
    var scene_1 = options.scene;
    if (scene != undefined && scene != "undefined") {
      mg_uid = scene;
    } else {
      if (scene_1 != undefined && scene_1 != "undefined") {
        mg_uid = scene_1;
      }
    }
    that.checkUserInfo();



  },

  // 检测是否需要登录
  checkUserInfo: function() {
    const that = this
    let openid = wx.getStorageSync('openid')
    if (openid) {
      app.globalData.openid = openid
      that.setData({
        openid,
      })
      let url = '/user_api/getInfoByOpenID';
      app.HttpPostSend(
        url, {
          openid: openid,
        },
        function(result_data) {
          if (result_data === '-10000') {
            wx.hideTabBar()
            that.setData({
              authSettingUser: 0
            });
          }
          if (result_data.msg != "success") {
            app.showTipMsg(result_data.msg);
          } else {
            if (!!result_data.data) { //如果后台有数据
              app.globalData.userInfo = {
                ...result_data.data
              }
              wx.setStorage({
                key: 'userInfo',
                data: JSON.stringify({
                  ...result_data.data
                })
              })
              that.setData({
                userInfo: result_data.data,
                u_id: app.globalData.userInfo.id
              })

              that.getManagers();
            } else { //如果后台无数据
              wx.login({
                success(res) {
                  let params = {
                    code: res.code
                  }
                  app.HttpGetSend(get_open_id, params, function(result) {

                    if (result.msg != "success") {
                      app.showTipMsg(result.msg);
                    } else {
                      app.globalData.openid = result.data.openid.openid;

                      wx.setStorage({
                        key: 'openid',
                        data: result.data.openid.openid
                      })
                      that.setData({
                        authSettingUser: 0,
                        openid: result.data.openid.openid
                      })

                    }
                  }, 1)
                }
              })
            }
          }
        })
    } else {

      wx.login({
        success(res) {
          let params = {
            code: res.code
          }
          app.HttpGetSend(get_open_id, params, function(result) {

            if (result.msg != "success") {
              app.showTipMsg(result.msg);
            } else {

              app.globalData.openid = result.data.openid.openid;
              wx.setStorage({
                key: 'openid',
                data: result.data.openid.openid
              })
              that.setData({
                authSettingUser: 0,
                openid: result.data.openid.openid
              })

            }
          }, 1)
        },
        fail: function(res) {
          console.log('失败');
        }
      })
    }
    let systemInfo = wx.getSystemInfoSync()
    app.globalData.systemInfo = systemInfo
    this.setData({
      systemInfo
    })
  },

  // 获取用户信息
  bindGetUserInfo: function(e) {
    const that = this
    if (e.detail.errMsg == "getUserInfo:ok") {
      wx.showTabBar()
      that.setData({
        authSettingUser: 1
      });
    } else {
      wx.hideTabBar()
    }
    let userInfo = e.detail.userInfo
    try {
      app.HttpPostSend(
        user_login, {
          openid: app.globalData.openid,
          username: userInfo.nickName,
          // phone: that.data.phone,
          // code: that.data.code,
          logo: userInfo.avatarUrl,
          sex: userInfo.gender
        },
        function(result_data) {
          if (result_data === '-10000') {
            wx.hideTabBar()
            that.setData({
              authSettingUser: 0
            });
          }
          if (result_data.msg != "success") {
            app.showTipMsg(result_data.msg);
          } else {
            app.globalData.authSettingUser = 1;
            let userInfo = {
              ...result_data.data
            }
            app.globalData.userInfo = userInfo
            wx.setStorage({
              key: 'userInfo',
              data: JSON.stringify(userInfo)
            })
            that.setData({
              userInfo: userInfo
            })
            that.getManagers();

          }
        })
    } catch (error) {

    }
  },

  getManagers: function() {
    var that = this;
    if (mg_uid == 0) {
      wx.showModal({
        title: '提示',
        content: '请用微信扫一扫',
        showCancel: false,
        success: function() {
          wx.navigateBack({
            delta: -1
          })
        }
      })
    } else {
      let url = '/user_api/getUserInfos';
      app.HttpPostSend(
        url, {
          uid: mg_uid,
        },
        function(result_data) {
          var re_data = result_data.data;
          that.setData({
            mg_info: re_data
          });
          app.globalData.SwitchTabParams.v_id = re_data.id
        }
      )
    }
  },
  money_input: function(e) {
    var that = this;
    var money = e.detail.value;

    that.setData({
      money: money
    });
    btn_status = 1;
  },
  integral_input: function(e) {
    var that = this;
    var integral = e.detail.value;
    that.setData({
      integral: integral
    });
    btn_status = 1;
  },

  desc_input: function(e) {
    var that = this;
    var desc = e.detail.value;
    that.setData({
      desc: desc
    });
    btn_status = 1;
  },

  pay: function() {
    const that = this;
    var money = that.data.money;
    if (btn_status > 0) {
      btn_status = 0;
      if (money > 0) {
        var url = '/order/add_scan_v4';
        var params = {

          integral: that.data.integral,
          uid: app.globalData.userInfo.id,
          price: money,
          desc: that.data.desc,
          mg_uid: app.globalData.SwitchTabParams.v_id,
          type: 3,
          invite_id: !!app.globalData.shareOptions.share_id ? app.globalData.shareOptions.share_id : app.globalData.shareOptions.invite_id,
          invite_uid: !!app.globalData.shareOptions.carte_id ? app.globalData.shareOptions.carte_id : '',
          timestamp: new Date().getTime(),
        };
        params.sign = app.getSign(params)
        wx.showLoading({
          title: '支付中',
        })
        app.HttpPostSend(url, params, function(res) {
          if (res.msg != "success") {
            // app.showTipMsg(res.msg);
            wx.showModal({
              title: '提示',
              content: res.msg,
              showCancel: false,
              success: function() {}
            })
            btn_status = 1;
            wx.hideLoading();
          } else {

            app.radarAdd(app.globalData.SwitchTabParams.v_id, 18, '', '', app.globalData.userInfo.logo)

            let params2 = {
              total_fee: 0,
              openid: app.globalData.openid,
              order_id: res.data,
              body: '到店支付',
              type: 1,
              order_source: 0,
              timestamp: new Date().getTime(),
            }
            params2.sign = app.getSign(params2)
            app.HttpPostSend(unified_order_v4, params2, function(unified_order_res) {
              wx.hideLoading();
              if (unified_order_res.msg != "success") {
                wx.showModal({
                  title: '提示',
                  content: unified_order_res.msg,
                  showCancel: false
                })

                btn_status = 1;
              } else {
                if (unified_order_res.data.success == 1) {
                  let order_arr = unified_order_res.data.order_arr
                  let signA = "appId=" + order_arr.appid + "&nonceStr=" + order_arr.noncestr + "&package=prepay_id=" + order_arr.prepayid + "&signType=MD5&timeStamp=" + order_arr.timestamp;
                  let signB = signA + "&key=" + unified_order_res.data.key
                  let new_pay_sign = MD5(signB)
                  console.log(new_pay_sign)
                  wx.requestPayment({
                    timeStamp: unified_order_res.data.order_arr.timestamp,
                    nonceStr: unified_order_res.data.order_arr.noncestr,
                    package: 'prepay_id=' + unified_order_res.data.order_arr.prepayid,
                    signType: 'MD5',
                    profit_sharing: 'Y',
                    paySign: new_pay_sign,
                    success(pay_res) {
                      console.log(pay_res)
                      wx.hideLoading();
                      // 雷达添加查看记录 -商品付款成功数
                      app.radarAdd(app.globalData.SwitchTabParams.v_id, 22, 0, money, app.globalData.userInfo.logo)
                      app.addlog(app.globalData.SwitchTabParams.v_id, '', app.globalData.userInfo.id, app.globalData.userInfo.username, app.globalData.userInfo.logo, 19, '')
                      // 发送模板消息-访客到访通知
                      app.sendTemplateMessage(app.globalData.SwitchTabParams.v_id, 10, '', '', res.data, '', '', 0);

                      wx.showModal({
                        title: '提示',
                        content: '支付成功',
                        showCancel: false,
                        success: function() {
                          wx.navigateTo({
                            url: '/shopPages/orderSuccess/orderSuccess?price=' + money + '&id=' + res.data + '&integral=' + JSON.stringify(that.data.integral) +'&freight_free=0'
                          })
                        }
                      })

                      btn_status = 1;
                    },
                    fail(err_res) {

                      btn_status = 1;
                    }
                  })
                } else {
                  app.radarAdd(app.globalData.SwitchTabParams.v_id, 22, 0, money, app.globalData.userInfo.logo)
                  app.addlog(app.globalData.SwitchTabParams.v_id, '', app.globalData.userInfo.id, app.globalData.userInfo.username, app.globalData.userInfo.logo, 19, '')
                  // 发送模板消息-访客到访通知
                  app.sendTemplateMessage(app.globalData.SwitchTabParams.v_id, 10, '', '', res.data, '', '', 0);
                  wx.showModal({
                    title: '提示',
                    content: '支付成功',
                    showCancel: false,
                    success: function() {
                      // wx.switchTab({
                      //   url: '/pages/person/person',
                      // })
                     
                      wx.navigateTo({
                        url: '/shopPages/orderSuccess/orderSuccess?price=' + money + '&id=' + res.data + '&integral=' + JSON.stringify(that.data.integral) + '&freight_free=0'
                      })
                    }
                  })

                  btn_status = 1;
                  wx.hideLoading();
                }

              }
            })
          }
        });

      } else {
        btn_status = 1;
        wx.showModal({
          title: '提示',
          content: '请输入金额',
          showCancel: false,
          success: function() {

          }
        })
      }
    }

  },
  bindperson:function(){
    wx.switchTab({
      url: '/pages/person/person',
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },


})